package com.hejiale.lease.web.admin.custom.converter;

import com.hejiale.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * @description: 自定义枚举类型转换器
 * @author: HeJiale
 * @since 2025/3/11 下午5:44
 */
@Component
public class StringToEnumConverterFactory implements ConverterFactory<String , BaseEnum> {
    /**
     * 匿名内部类
     * @param targetType
     * @返回值 返回一个converter转换器
     */
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String code) {
                T[] enumConstants = targetType.getEnumConstants();
                for (T enumConstant : enumConstants){
                    if (enumConstant.getCode().equals(Integer.valueOf(code))){
                        return enumConstant;
                    }
                }
                throw new IllegalArgumentException("code" + code + " 非法");
            }
        };
    }

}
